package com.loan.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.loan.common.constant.Constants;
import com.loan.common.core.page.PageData;
import com.loan.common.service.CrudService;
import com.loan.common.utils.BeanCopyUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * CURD基础服务类
 * @author shiguang
 */
public abstract class CrudServiceImpl<M extends BaseMapper<T>,T,D> extends BaseServiceImpl<M,T> implements CrudService<T, D> {

    protected Class<D> currentDtoClass(){
        return (Class<D>) ReflectionKit.getSuperClassGenericType(getClass(),getClass(),2);
    }

    @Override
    public PageData<D> page(Map<String,Object> params){
        IPage<T> page = baseMapper.selectPage(
                getPage(params, Constants.CREATE_TIME,false),
                getWrapper(params)
        );
        return getPageData(page,currentDtoClass());
    }

    @Override
    public List<D> list(Map<String,Object> params){
        List<T> entityList = baseMapper.selectList(getWrapper(params));
        return BeanCopyUtils.copyList(entityList,currentDtoClass());
    }

    public abstract QueryWrapper<T> getWrapper(Map<String,Object> params);

    @Override
    public D get(Long id){
        T entity = baseMapper.selectById(id);
        return BeanCopyUtils.copy(entity,currentDtoClass());
    }

    @Override
    public void save(D dto){
        T entity = BeanCopyUtils.copy(dto,currentModelClass());
        insert(entity);
    }

    @Override
    public void update(D dto){
        T entity = BeanCopyUtils.copy(dto,currentModelClass());
        updateById(entity);
    }

    @Override
    public void delete(Long[] ids){
        baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

}
